<?php
session_start();

// 检查是否已安装
$install_file = '../data/installed.txt';
if (!file_exists($install_file)) {
    header('Location: ../install/');
    exit;
}

// 加载配置
if (!file_exists('../data/config.php')) {
    die('配置文件不存在，请先完成安装');
}
require_once '../data/config.php';

// 数据库连接
try {
    $pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("数据库连接失败: " . $e->getMessage());
}

// 获取用户IP
function getUserIP() {
    $ip_keys = ['HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'HTTP_CLIENT_IP', 'REMOTE_ADDR'];
    foreach ($ip_keys as $key) {
        if (!empty($_SERVER[$key])) {
            $ip = $_SERVER[$key];
            if (strpos($ip, ',') !== false) {
                $ip = trim(explode(',', $ip)[0]);
            }
            if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                return $ip;
            }
        }
    }
    return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
}

$user_ip = getUserIP();
$user_dir = "../users/" . $user_ip;

// 创建用户目录
if (!file_exists($user_dir)) {
    mkdir($user_dir, 0755, true);
}

// 记录用户到数据库
$stmt = $pdo->prepare("INSERT IGNORE INTO users (ip_address) VALUES (?)");
$stmt->execute([$user_ip]);

// 获取聊天历史
$stmt = $pdo->prepare("SELECT message, response, timestamp FROM chat_history WHERE user_ip = ? ORDER BY timestamp ASC");
$stmt->execute([$user_ip]);
$chat_history = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 处理API请求
function getAIResponse($message, $history, $api_key, $base_url, $model) {
    // 准备消息历史
    $messages = [
        ['role' => 'system', 'content' => 'You are a helpful assistant.']
    ];
    
    // 添加历史记录
    foreach ($history as $chat) {
        $messages[] = ['role' => 'user', 'content' => $chat['message']];
        $messages[] = ['role' => 'assistant', 'content' => $chat['response']];
    }
    
    // 添加当前消息
    $messages[] = ['role' => 'user', 'content' => $message];

    $curl = curl_init();
    
    curl_setopt_array($curl, [
        CURLOPT_URL => $base_url . "/chat/completions",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode([
            'model' => $model,
            'messages' => $messages,
            'temperature' => 0.7,
            'max_tokens' => 1000
        ]),
        CURLOPT_HTTPHEADER => [
            "Content-Type: application/json",
            "Authorization: Bearer $api_key"
        ],
        CURLOPT_TIMEOUT => 60
    ]);
    
    $response = curl_exec($curl);
    $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);
    
    if ($http_code === 200) {
        $data = json_decode($response, true);
        if (isset($data['choices'][0]['message']['content'])) {
            return trim($data['choices'][0]['message']['content']);
        } else {
            return "错误：API响应格式不正确";
        }
    } else {
        return "错误：API请求失败，HTTP状态码 $http_code";
    }
}

// 处理用户消息
if ($_POST && isset($_POST['message']) && !empty(trim($_POST['message']))) {
    $user_message = trim($_POST['message']);
    
    // 获取AI响应
    $ai_response = getAIResponse($user_message, $chat_history, $api_key, $base_url, $default_model);
    
    // 保存到数据库
    $stmt = $pdo->prepare("INSERT INTO chat_history (user_ip, message, response) VALUES (?, ?, ?)");
    $stmt->execute([$user_ip, $user_message, $ai_response]);
    
    // 重定向以避免重复提交
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// 获取当前会话的聊天记录
$stmt = $pdo->prepare("SELECT message, response, timestamp FROM chat_history WHERE user_ip = ? ORDER BY timestamp ASC");
$stmt->execute([$user_ip]);
$chat_history = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>lanxAI - 首个览星自研发AI</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            height: 100vh;
            display: flex;
            flex-direction: column;
        }
        
        .header {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: white;
        }
        
        .header h1 {
            font-size: 1.5em;
            font-weight: 600;
        }
        
        .header .user-info {
            font-size: 0.9em;
            opacity: 0.8;
        }
        
        .chat-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            max-width: 1200px;
            width: 100%;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            margin-top: 20px;
            margin-bottom: 20px;
        }
        
        .chat-history {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            background: #f9f9f9;
        }
        
        .message {
            margin-bottom: 15px;
            padding: 10px 15px;
            border-radius: 10px;
            max-width: 80%;
            word-wrap: break-word;
            line-height: 1.5;
        }
        
        .user-message {
            background: #667eea;
            color: white;
            margin-left: auto;
            text-align: right;
        }
        
        .ai-message {
            background: #e9ecef;
            color: #333;
            margin-right: auto;
        }
        
        .input-area {
            display: flex;
            padding: 15px;
            background: white;
            border-top: 1px solid #eee;
        }
        
        .input-area input {
            flex: 1;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 25px;
            font-size: 16px;
            outline: none;
        }
        
        .input-area button {
            margin-left: 10px;
            padding: 12px 25px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 16px;
        }
        
        .input-area button:hover {
            opacity: 0.9;
        }
        
        .footer {
            text-align: center;
            padding: 15px;
            color: white;
            font-size: 14px;
        }
        
        .timestamp {
            font-size: 0.7em;
            opacity: 0.7;
            margin-top: 5px;
            display: block;
        }
        
        .language-toggle {
            margin-right: 20px;
        }
        
        .language-toggle button {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            border: 1px solid rgba(255, 255, 255, 0.3);
            padding: 5px 10px;
            border-radius: 5px;
            cursor: pointer;
            margin-left: 5px;
        }
        
        .language-toggle button.active {
            background: white;
            color: #667eea;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>lanxAI - 首个览星自研发AI</h1>
        <div class="language-toggle">
            <button id="zhBtn" class="active">中文</button>
            <button id="enBtn">English</button>
        </div>
        <div class="user-info">IP: <?php echo htmlspecialchars($user_ip); ?></div>
    </div>
    
    <div class="chat-container">
        <div class="chat-history" id="chatHistory">
            <?php if (count($chat_history) > 0): ?>
                <?php foreach ($chat_history as $chat): ?>
                    <div class="message user-message">
                        <?php echo nl2br(htmlspecialchars($chat['message'])); ?>
                        <span class="timestamp"><?php echo date('Y-m-d H:i:s', strtotime($chat['timestamp'])); ?></span>
                    </div>
                    <div class="message ai-message">
                        <?php echo nl2br(htmlspecialchars($chat['response'])); ?>
                        <span class="timestamp"><?php echo date('Y-m-d H:i:s', strtotime($chat['timestamp'])); ?></span>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="message ai-message">
                    您好！我是lanxAI，览星自研发的AI助手。请问有什么可以帮助您的吗？
                    <span class="timestamp"><?php echo date('Y-m-d H:i:s'); ?></span>
                </div>
            <?php endif; ?>
        </div>
        
        <form class="input-area" method="post">
            <input type="text" name="message" placeholder="输入您的消息..." required autocomplete="off">
            <button type="submit">发送</button>
        </form>
    </div>
    
    <div class="footer">
        <p>LANX开源AI</p>
    </div>

    <script>
        // 自动滚动到最新消息
        const chatHistory = document.getElementById('chatHistory');
        chatHistory.scrollTop = chatHistory.scrollHeight;
        
        // 语言切换功能
        document.getElementById('zhBtn').addEventListener('click', function() {
            this.classList.add('active');
            document.getElementById('enBtn').classList.remove('active');
            // 这里可以添加实际的语言切换逻辑
        });
        
        document.getElementById('enBtn').addEventListener('click', function() {
            this.classList.add('active');
            document.getElementById('zhBtn').classList.remove('active');
            // 这里可以添加实际的语言切换逻辑
        });
    </script>
</body>
</html>